#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:ouyang time:2023/4/5

import json
import threading
import time
import socket
import base64
import os
import copy
import signal
from collections import deque


class Broadcast(threading.Thread):
    """
    广播车辆的信息
    """

    def __init__(self, user_type, caller_id, user_ip):

        threading.Thread.__init__(self)

        """ 定义常量 """
        self.run_environment = 'pc'
        self.PC_Broadcast_IP = '<broadcast>'
        self.user_type = user_type
        self.user_id = caller_id
        self.user_ip = user_ip
        if self.user_type == "CAR":
            self.CAR_ID = self.user_type + str(caller_id)
            self.Car_Broadcast_IP = self.user_ip
            self.CAR_COVER_PORT = 61121
            self.CAR_UDP_PORT = 1060
            self.HOST_IP = '127.0.0.1'
            self.client_port = self.CAR_UDP_PORT
        else:
            self.RSU_ID = self.user_type + str(caller_id)
            self.RSU_Broadcast_IP = self.user_ip
            self.RSU_COVER_PORT = 61121
            self.RSU_UDP_PORT = 1060
            self.HOST_IP = '127.0.0.1'
            self.client_port = self.RSU_UDP_PORT

        """ 选择运行环境 """
        if self.run_environment == 'pc':
            self.car_connect_ip = self.HOST_IP
            self.broadcast_network = self.PC_Broadcast_IP

        """初始化UDP客户端"""
        self.udp_client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.udp_client.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
        self.bc_json = " "
        self.broadcast_init()

        """socket连接状态、数据缓存"""
        self.connect_sta = 0     # 连接状态变为断开状态
        self.thread_run = 0      # 线程结束状态

        """广播数据变量"""
        self.rsu_state = 0        # 连接RSU的状态
        self.time_stamp = 0       # 广播时间戳
        self.mec_delay = 0        # MEC时延
        self.remain_route = 0     # 剩余路由接入点
        self.credibility = 0      # 可信度
        self.speed = 0            # 车辆速度
        self.bc_ttl = 5           # 广播传递剩余跳数

    def broadcast_init(self):
        """
        用于发送广播信息，发送服务端地址，用于客户端建立连接
        :return:
        """

    def send_broadcast(self, data):
        """
        :param data: 字符串类型数据
        :return: 无
        """
        self.udp_client.sendto(data.encode('utf-8'), (self.broadcast_network, self.client_port))

    def structure_data(self):
        """
        :return: 构造好的json数据
        """
        broadcast_data = {}
        broadcast_data.clear()
        if self.user_type == "CAR":
            broadcast_data['ID'] = self.CAR_ID
            broadcast_data['IP'] = self.car_connect_ip
            broadcast_data['RSU_STA'] = self.rsu_state
            broadcast_data['TIME_STAMP'] = self.time_stamp
            broadcast_data['MEC_DELAY'] = self.mec_delay
            broadcast_data['TIME_STAMP'] = self.time_stamp
            broadcast_data['REMAIN_ROUTE'] = self.remain_route
            broadcast_data['CREDIBILITY'] = self.credibility
            broadcast_data['SPEED'] = self.speed
            broadcast_data['BC_TTL'] = self.bc_ttl
            broadcast_data['PORT'] = self.CAR_COVER_PORT
        else:
            broadcast_data['ID'] = self.RSU_ID
            broadcast_data['IP'] = self.user_ip
            broadcast_data['TIME_STAMP'] = self.time_stamp
            broadcast_data['PORT'] = self.RSU_COVER_PORT
        bc_json_data = json.dumps(broadcast_data)  # dumps是字典转字符串，json就是字符串
        # print(bc_json_data)

        return bc_json_data

    def run(self):
            self.udp_server_task()

    def udp_server_task(self):

        while True:
            try:
                self.update_info()
                self.send_broadcast(self.structure_data())
                time.sleep(1)

            except Exception as e:
                print(e)
                return 0

    def update_info(self):
        self.time_stamp = round(time.time(), 4)


if __name__ == '__main__':
    car = Broadcast("CAR", 1, "127.0.0.1")
    car.run()

